package animation.sort.algorithms;

import animation.sort.algorithms.RandomQuickSort;
import animation.core.AlgorithmMonitorModel;

/**
 * Created by IntelliJ IDEA.
 * User: emilio
 * Date: Aug 12, 2004
 * Time: 11:57:23 AM
 * To change this template use File | Settings | File Templates.
 */
public class MedianOf3QuickSort
        extends RandomQuickSort
{
    public String toString()
    {
        return "QSort (Median of 3)";
    }

    void sort(int array[], int low, int high)
            throws Exception
    {
        markBox(low, high);

        int n = high - low + 1;
        if (n <= 1) {
        }
        else if (n == 2) {
            swapIfGreater(array, low, high);
        }
        else {

            int m = (high + low) / 2;
            monitorModel.setVariableValue("m", m);
            if (n == 3) {
                sort3(array, low, m, high);
            }
            else {
                if (n > 5)
                    sort3(array, low, high, m);
                int pos = partition(array, low, high);
                sort(array, low, pos - 1);
                sort(array, pos + 1, high);
            }
        }
    }

    protected void sort3(int[] array, int low, int m, int high)
            throws Exception
    {
        swapIfGreater(array, low, m);
        swapIfGreater(array, m, high);
        swapIfGreater(array, low, m);
    }

    protected void swapIfGreater(int[] array, int low, int high)
            throws Exception
    {
        if (greater(array, low, high)) {
            swap(array, low, high);
        }
    }

    protected void registerSpecificVariables(AlgorithmMonitorModel monitorModel) {
        super.registerSpecificVariables(monitorModel);
        monitorModel.registerVariable("m", "0");
    }

}
